<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="op2-analysis-step">
    <div class="steps">
      <el-steps :active="active" style="width: 100%" align-center>
        <el-step title="结果文件选择" />
        <el-step title="对比条目设置" />
        <el-step title="单元/节点清单上传" />
        <el-step title="完成" />
      </el-steps>
    </div>
    <div class="choose-file" v-show="active === 1" v-loading="uploadLoading">
      <div class="upload_content">
        <el-form size="small" label-width="120">
          <el-form-item label="分析事项名称：" required>
            <el-input style="width: 480px" v-model="analysisForm.taskName" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="部段名称：" required>
            <el-select style="width: 480px" v-model="analysisForm.sectionNumbers" multiple clearable placeholder="请选择" @change="sectionChange">
              <el-option v-for="(item, index) in props.sectionList" :label="item.name" :value="item.mark" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择结果库：" required>
            <el-button type="primary" icon="Document" size="small" @click="chooseFile">添加</el-button>
            <el-table :data="analysisForm.stepOne" style="width: 100%; margin-top: 5px;">
              <el-table-column type="index" label="序号" width="100">
                <template #default="scope">
                  <el-icon v-if="scope.row.baseRound && scope.row.baseRound == 1" :size="20" color="red" style="margin-top: 5px;">
                    <Guide />
                  </el-icon>
                  <span style="margin-left: 5px;">{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="OP2文件名称" align="center" prop="fileName"></el-table-column>
              <el-table-column prop="modelNumber" label="机型" width="180">
              </el-table-column>
              <el-table-column prop="batchNumber" label="批次" width="100">
              </el-table-column>
              <el-table-column prop="roundNumber" label="轮次" width="100">
              </el-table-column>
              <el-table-column prop="remarks" label="备注" width="100">
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-link style="margin-right: 10px;" size="small" type="danger" @click="handleRemove(scope.$index, scope.row)">移除</el-link>
                  <el-link v-if="!scope.row.baseRound || scope.row.baseRound == 2" size="small" type="primary" @click="setBase(scope.$index, scope.row)">设为基准轮次</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="uploadLoading" class="entries-setting" v-show="active === 2">
      <el-form size="small" label-width="120">
        <el-form-item label="对比条目配置：" required>
          <el-button type="primary" icon="Document" size="small" @click="addEntries">添加</el-button>
          <el-table :data="stepTwoList" style="width: 100%">
            <el-table-column type="index" label="序号" width="100">
            </el-table-column>
            <el-table-column prop="itemName" label="对比条目">
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="danger" @click="handleItemDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="stepTwoListHasDel.length > 0" style="width: 100%;">
            <h3>已剔除默认条目列表：</h3>
            <el-table :data="stepTwoListHasDel" style="width: 100%">
              <el-table-column type="index" label="序号" width="100">
              </el-table-column>
              <el-table-column prop="itemName" label="对比条目">
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button size="small" type="warning" @click="cancelDelete(scope.$index, scope.row)">撤销</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="unit-upload" v-show="active === 3" v-loading="uploadLoading" element-loading-text="数据导入中...">
      <el-form size="small" label-width="120">
        <el-form-item label="单元/节点清单：" required>
          <el-upload 
            class="upload-demo" 
            style="width:480px;" 
            :multiple="false"
            :limit="1" 
            :file-list="uploadFiles" 
            :beforeUpload="beforeUpload" 
            :on-change="handleChange"
            :on-success="handleSuccess"
            :on-error="handleError"
            :http-request="componentImport"
            accept=".xlsx,.xls">
            <el-button size="small">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip" style="display: block;">
                支持扩展名：.xls, .xlsx。<br><el-link style="font-size: 14px;" size="small" type="primary" @click="downloadTemplate">下载模板</el-link>
              </div>
            </template>
          </el-upload>
          
        </el-form-item>
      </el-form>
    </div>
    <div class="upload_success" v-show="active === 4">
      <div class="upload_success_message">
        <el-icon size="48" color="#67C23A"><CircleCheck /></el-icon>
        <h3 class="res-statistic">
          成功创建结果文件分析事项
        </h3>
      </div>
      <!-- <div class="model-batch">
        <el-button type="primary" size="small">点击返回列表查看分析进度</el-button>
      </div> -->
    </div>
    <div class="option_btn">
      <el-button size="small" @click="cancel" v-show="active < 4" :disabled="uploadLoading">返回首页</el-button>
      <el-button size="small" :disabled="uploadLoading" v-show="[2, 3].includes(active)" @click="step('pre', 1)">返回上一步</el-button>
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="[1, 2, 3].includes(active)" @click="step('next', 2)">下一步</el-button>
      <!-- <el-button size="small" type="primary" :disabled="uploadLoading" v-show="active === 2" @click="comfirmImport">确认上传</el-button> -->
      <el-button size="small" type="primary" v-show="active === 4" @click="finish">完成</el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" title="文件解析中..." width="500" :show-close="false">
      <el-table v-loading="dialogFormVisible" :data="[]" style="width: 100%">
      </el-table>
      <p style="text-align: center;">文件解析中，请耐心等待。</p>
    </el-dialog>
    <AddObject 
      v-if="addObjectVisible"
      :dialogVisible="addObjectVisible"
      :sectionNames="analysisForm.sectionNames"
      @handleEvent="handleEvent"
    />
    <SetEntries
      v-if="setEntriesVisible"
      :dialogVisible="setEntriesVisible"
      @handleEvent="handleEvent"
    />
  </div>
</template>
<script  setup name="Op2AnalysisStep">
import AddObject from './AddObject.vue';
import SetEntries from './SetEntries.vue';
import { downloadFile } from '@/utils/index';
import { uploadCompareEntries, downloadOp2ResultTemplate, addOp2CompareTask, getOp2CompareTaskDetail, getCompareDefaultItemList } from '@/api/dataAcquisition';

const emits = defineEmits(['handleEvent']);
const props = defineProps(['sectionList', 'rowId']);
const uploadLoading = ref(false);
const addObjectVisible = ref(false);
const setEntriesVisible = ref(false);
const active = ref(1);
const chooseData = ref(null);
const computedData = ref(null);
const checkedTreeData = ref([]);
const computedUpdate = ref(false);
const analysisForm = ref({
  taskName: undefined,
  sectionNames: [],
  sectionNumbers: [],
  stepOne: [],
  stepTwo: [],
  get_id: undefined,
  currentStep: 1,
  maxStep: 1,
  stepThree: {
    templateUploadUrl: undefined,
  }
})
const sectionList = ref([]);
const batchList = ref([]);
const uploadFiles = ref([]);
const dialogFormVisible = ref(false);
const handleZipData = ref(null);
// 导入确认数据
const confirmImportTableData = ref([]);
const handleModelData = ref(null);
const uploadResult = ref(null); // 上传结果
const filterCount = ref(0);
const notFilterCount = ref(0);
const totalCount = ref(0);
const treeVo = ref([]);
const stepTwoList = ref([]);
const stepTwoListHasDel = ref([]);
const defaultItemList = ref([]);
const downloadTemplate = () => {
  downloadOp2ResultTemplate({
    id: analysisForm.value._id
  }).then(res => {
    downloadFile(res, `节点清单模板`, 'xlsx');
  })
}
const setBase = (index, row) => {
  analysisForm.value.stepOne.forEach(item => {
    item.baseRound = 2;
  })
  row.baseRound = 1;
}
const chooseFile = () => {
  if (!analysisForm.value.sectionNames || analysisForm.value.sectionNames.length <= 0) {
    ElMessage.error('请先选择部段名称');
    return false;
  }
  addObjectVisible.value = true;
}
const sectionChange = (val) => {
  if (val && val.length > 0) {
    analysisForm.value.sectionNames = val.map(item => {
      return props.sectionList.find(el => el.mark == item).name; 
    })
  }
}
const addEntries = () => {
  setEntriesVisible.value = true; 
}
const querySearch = (queryString, cb) => {
  const results = queryString
    ? batchList.value.filter(item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
    : batchList.value
    console.log('result', results)
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString) => {
  return (item) => {
    return (
      item.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
const handleRemove = (index, row) => {
  analysisForm.value.stepOne.splice(index, 1);
}
const handleItemDelete = (index, row) => {
  stepTwoList.value.splice(index, 1);
  // const codeList = stepTwoList.value.map(item => item.itemCode);
  row.type == 1 && stepTwoListHasDel.value.push(row);  
  // defaultItemList.value.filter(item => !codeList.includes(item.itemCode));
}
// 撤销删除
const cancelDelete = (index, row) => {
  stepTwoListHasDel.value.splice(index, 1);
  stepTwoList.value.push(row);
}
const handleChange = (file, fileList) => {
  uploadFiles.value = fileList;
};
const handleSuccess = (response, file, fileList) => {};
const handleError = (error, file, fileList) => {};
const beforeUpload = (file) => {
  let isFile = file.name.split('.')[file.name.split('.').length - 1] == 'xls' || file.name.split('.')[file.name.split('.').length - 1] == 'xlsx';
  if (!isFile) {
    ElMessage.error('导入文件格式不正确');
    return false;
  }
  return isFile;
};
const componentImport = async (file, fileList) => {
  
  const fd = new FormData();
  fd.append('file', file.file);
  fd.append('taskId', analysisForm.value._id);
  uploadCompareEntries(fd).then(res => {
    if (res) {
      analysisForm.value.stepThree.templateUploadUrl = res.data?.fileUrl;
      ElMessage({ showClose: true, message: '文件上传成功。', type: 'success' });
    } 
  })
};

const step = async (type) => {
  if (type === 'next') {
    if ([1,2,3].includes(active.value)) {
      await saveCurrentStep(active.value)
    }
    active.value ++;
  } else {
    active.value--;
  }
};

// 数据保存
const saveCurrentStep = async (stepNum) => {
  if (stepNum == 2) {
    if (stepTwoList.value.length == 0) {
      ElMessage({ showClose: true, message: '请先选择对比条目', type: 'error' });
      return false;
    }
    analysisForm.value.stepTwo = stepTwoList.value
  }
  
  analysisForm.value.currentStep = active.value;
  await addOp2CompareTask(analysisForm.value).then(res => {
    if (res) {
      analysisForm.value = res.data;
    } 
  })
}

// 确认上传
const comfirmImport = () => {
  if (handleModelData.value.initTableData.length === 0) {
    ElMessage({ showClose: true, message: '文件为空，请重新上传。', type: 'error' });
    return; 
  }
  uploadLoading.value = true;
  confirmUpload({
    tableName: props.tableName,
    boList: handleModelData.value.initTableData
  }).then(res => {
    if (res) {
      uploadLoading.value = false;
      uploadResult.value = res.data;
      totalCount.value = res.data.countVo.totalCount;
      notFilterCount.value = res.data.countVo.notFilterCount;
      filterCount.value = res.data.countVo.filterCount;
      treeVo.value = [res.data.treeVo];
      active.value++;
    }
  }).finally(() => {
    uploadLoading.value = false;
  })
}
const handleEvent = (data) => {
  if (data.type === 'AddObj') {
    let ids = analysisForm.value.stepOne.map(item => item._id);
    analysisForm.value.stepOne = [
      ...analysisForm.value.stepOne,
      ...data?.data?.hasChooseFileList.filter(item => !ids.includes(item._id))
    ];
    // analysisForm.value.sectionNumbers = data?.data?.formData.sectionNumbers;
    addObjectVisible.value = false;
  } else if (data.type === 'AddEnt') {
    if (stepTwoList.value.some(item => item.itemCode == data.data.itemCode)) {
      ElMessage.error('条目名称重复');
      return false;
    }
    stepTwoList.value.push(data.data);
    setEntriesVisible.value = false;
  } else {
    addObjectVisible.value = false;
    setEntriesVisible.value = false;
  }
};
// 获取默认条目列表
const getDefaultItemList = async () => {  
  await getCompareDefaultItemList().then(res => {
    if (res) {
      // analysisForm.value.stepTwo = res.data;
      defaultItemList.value = JSON.parse(JSON.stringify(res.data));
      stepTwoList.value = res.data;
      stepTwoListHasDel.value = [];
    }
  })
}
// 完成组建
const finish = () => {
  emits('handleEvent', { component: 'Analysis', type: 'finish', tableName: props.tableName });
};
// 取消
const cancel = () => {
  emits('handleEvent', { component: 'Analysis', type: 'cancel', tableName: props.tableName });
};
onMounted(async () => {
  await getDefaultItemList();
  if (props.rowId) {
    getOp2CompareTaskDetail({id: props.rowId}).then(res => {
      if (res) {
        analysisForm.value = res.data;
        active.value = res.data.maxStep;
        if (res.data.stepTwo && res.data.stepTwo.length > 0) {
          stepTwoList.value = res.data.stepTwo;
          const idList = res.data.stepTwo.map(item => item.id);
          stepTwoListHasDel.value = defaultItemList.value.filter(item => !idList.includes(item.id) && item.type == 1);
        }
      }
    })
  }
});
</script>
<style lang="scss" scoped>
.op2-analysis-step {
  padding: 10px;
  width: 100%;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: scroll;
  font-size: 12px;
  .steps {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
  }
  .choose-file {
    // width: 800px;
    margin-top: 20px;
    .upload_content {
      // width: 800px;
      // height: 475px;
      text-align: center;
      .upload_form {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
    }
  }
  .entries-setting, .unit-upload {
    margin-top: 20px;
  }
  .upload_list,
  .upload_success {
    margin-top: 10px;
    // overflow: scroll;
    // min-height: calc(100vh - 251px);
    width: 100%;
  }
  .model-batch {
    padding: 10px;
    label {
      font-size: 16px;
    }
    span {
      margin-right: 20px;
      font-size: 14px;
    }
  }
  .option_btn {
    margin-top: 20px;
  }
  .upload_success {
    margin-top: 10px;
    .upload_success_message {
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  .finish {
    width: 600px;
    margin-top: 20px;
  }
  :deep(.el-step__title) {
    font-size: 12px;
  }
}
</style>
